/*
 * @Description:
 * @Version: 1.0
 * @Autor: ziwei
 * @Date: 2021-06-25 20:17:03
 * @LastEditors: ziwei
 * @LastEditTime: 2022-02-10 16:31:13
 */
const { runLoaders } = require("./load-runner");
const path = require("path");
const fs = require("fs");

//要加载文件的绝对路径
const entryFile = path.resolve(__dirname, "src/index.js");
//post(后置)+inline(行内)+normal(正常)+pre(前置)
let request = `inline-loader1!inline-loader2!${entryFile}`;

//规则
let rules = [
  {
    test: /.\js$/,
    use: ["normal-loader1", "normal-loader2"],
  },
  {
    test: /\.js$/,
    enforce: "post",
    use: ["post-loader1", "post-loader2"],
  },
  {
    test: /\.js$/,
    enforce: "pre",
    use: ["pre-loader1", "pre-loader2"],
  },
];

/* 在加载模块的时候 可以指定一些前缀
 * ！ noAutoLoaders 不要普通的
 * !! noPre
 */
//切割特殊符号再进行分割
let parts = request.replace(/^-?!+/,'').split("!"); //["inline1-loader"]
let resource = parts.pop(); //弹出最后一个元素 entryFile

let inlineLoaders = parts; //[inline-loader1,inline-loader2]
let preLoaders = [],
  normalLoaders = [],
  postLoaders = [];
//匹配规则
for (let i = 0; i < rules.length; i++) {
  let rule = rules[i];
  if (rule.test.test(resource)) {
    if (rule.enforce === "pre") {
      preLoaders.push(...rule.use);
    } else if (rule.enforce === "post") {
      postLoaders.push(...rule.use);
    } else {
      normalLoaders.push(...rule.use);
    }
  }
}

console.log("inlineLoaders", inlineLoaders);
console.log("preLoaders", preLoaders);
console.log("postLoaders", postLoaders);
console.log("normalLoaders", normalLoaders);

let loaders = []
if(request.startsWith('!!')){
  loaders = [...inlineLoaders];
}else if(request.startsWith('-!')){
  loaders = [...postLoaders,...inlineLoaders];
}else if(request.startsWith('!')){
  loaders = [...postLoaders,...inlineLoaders,...preLoaders];
}else{
  loaders = [...postLoaders,...inlineLoaders,...normalLoaders,...preLoaders];
}

let resolveLoader = loader=>path.resolve(__dirname,'loaders-chain',loader)
//把loader数组从名称变成绝对路径
loaders = loaders.map(resolveLoader)
runLoaders(
  {
    resource, //将要加载和转换的模块路径
    loaders, //使用哪些loader来进行转换
    context: { name: "zhufeng" }, //保存一些状态和值
    readResource: fs.readFile.bind(fs), //可以自定义读取文件的方法
  },
  (err, result) => {
    console.log(err);//运行报错
    console.log(result);//运行的结果
    //没有读取文件toString就是undefined
    console.log(result.resourceBuffer?result.resourceBuffer.toString('utf8'):null)//读到原始的文件
  }
);
